package me.zhengjie.modules.hanzi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.hanzi.domain.Category;
import me.zhengjie.modules.hanzi.domain.HanziCharacter;
import me.zhengjie.modules.hanzi.mapper.CategoryMapper;
import me.zhengjie.modules.hanzi.mapper.CharacterMapper;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CategoryService extends ServiceImpl<CategoryMapper, Category> {
    private final CategoryMapper categoryMapper;
    private final CharacterMapper characterMapper;

    public List<Category> getCategories() {
        // 获取所有分类，并更新每个分类的汉字数量
        List<Category> categories = categoryMapper.selectList(null);
        for (Category category : categories) {
            int count = characterMapper.selectCount(
                new QueryWrapper<HanziCharacter>()
                    .eq("category_id", category.getCategoryId())
            ).intValue();
            category.setCount(count);
        }
        return categories;
    }

    public Category getCategory(String categoryId) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        return categoryMapper.selectOne(wrapper);
    }

    public Page<HanziCharacter> getCategoryCharacters(String categoryId, int page, int limit) {
        QueryWrapper<HanziCharacter> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId)
              .orderByAsc("stroke_count"); // 按笔画数排序
        return characterMapper.selectPage(new Page<>(page, limit), wrapper);
    }
} 